package com.ny.view;

import com.ny.dao.impl.ManagerDaoImpl;
import com.ny.entity.Manager;
import com.ny.entity.Order;
import com.ny.entity.Product;
import com.ny.entity.Student;
import com.ny.service.ManagerService;
import com.ny.service.OrderService;
import com.ny.service.ProductService;
import com.ny.service.StudentService;
import com.ny.service.impl.ManagerServiceImpl;
import com.ny.service.impl.OrderServiceImpl;
import com.ny.service.impl.ProductServiceImpl;
import com.ny.service.impl.StudentServiceImpl;
import com.ny.until.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

public class IndexView {
    private static StudentService studentService = new StudentServiceImpl();

    private static ProductService productService = new ProductServiceImpl();

    private static OrderService orderService = new OrderServiceImpl();
    private static ManagerService managerService = new ManagerServiceImpl();

    public static void main(String[] args) throws SQLException {
        while (true) {
            System.out.println("欢迎使用学生系统");
            System.out.println("1. 用户登录");
            System.out.println("2. 注册");
            System.out.println("3. 管理员登录");
            System.out.println("4. 退出");

            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();

            switch (n) {
                case 1:
                    System.out.print("请输入用户名：");
                    String sname = scanner.next();
                    System.out.print("请输入密码：");
                    String spassword = scanner.next();

                    Student student = studentService.selectStudent(sname, spassword);
                    if (student != null) {
                        System.out.println("登录成功！");
                        boolean logout = false;
                        while (!logout) {
                            System.out.println("\n请选择操作：");
                            System.out.println("1. 查看商品并购买");
                            System.out.println("2. 修改个人信息");
                            System.out.println("3. 退出登录");
                            System.out.print("请输入选项：");

                            int choice = scanner.nextInt();
                            scanner.nextLine();

                            switch (choice) {
                                case 1:

                                    List<Product> productList = productService.selectAllProduct();
                                    System.out.println("\n商品列表：");
                                    System.out.println("ID\t名称\t\t价格\t库存\t类别\t描述");
                                    for (Product product : productList) {
                                        System.out.printf("%d\t%s\t%.2f\t%d\t%s\t%s%n",
                                                product.getProductId(),
                                                product.getProductName(),
                                                product.getPrice(),
                                                product.getStock(),
                                                product.getCategory(),
                                                product.getDescription());
                                    }

                                    System.out.print("\n请选择购买的商品编号：");
                                    int productId = scanner.nextInt();
                                    scanner.nextLine(); // 清除输入缓冲区

                                    System.out.print("请选择购买的数量：");
                                    int num = scanner.nextInt();
                                    scanner.nextLine();

                                    Product selectedProduct = null;
                                    for (Product p : productList) {
                                        if (p.getProductId() == productId) {
                                            selectedProduct = p;
                                            break;
                                        }
                                    }

                                    if (selectedProduct == null) {
                                        System.out.println("商品不存在！");
                                        break;
                                    }

                                    if (num <= 0) {
                                        System.out.println("数量必须大于0！");
                                        break;
                                    }

                                    if (num > selectedProduct.getStock()) {
                                        System.out.println("库存不足！");
                                        break;
                                    }

                                    Order order = new Order();
                                    order.setStudentId(student.getStudentId());
                                    order.setProductId(productId);
                                    order.setNumber(num);
                                    order.setTotalPrice(num * selectedProduct.getPrice());

                                    int result = orderService.insertOrder(order);
                                    if (result > 0) {
                                        System.out.println("购买成功！");
                                        System.out.println("购买数量为"+result+"\t剩余库存为"+num);
                                    } else {
                                        System.out.println("购买失败！");
                                    }
                                    break;

                                case 2:
                                    System.out.println("\n修改个人信息（直接回车保留原值）");
                                    System.out.print("请输入新密码：");
                                    String newPassword = scanner.nextLine();

                                    System.out.print("请输入新手机号：");
                                    String newPhone = scanner.nextLine();

                                    if (!newPassword.isEmpty()) {
                                        student.setPassword(newPassword);
                                    }
                                    if (!newPhone.isEmpty()) {
                                        student.setPhone(newPhone);
                                    }

                                    try (Connection conn = new DbUtil().getCon()) {
                                        String sql = "UPDATE students SET password = ?, phone = ? WHERE student_id = ?";
                                        try (PreparedStatement ps = conn.prepareStatement(sql)) {
                                            ps.setString(1, student.getPassword());
                                            ps.setString(2, student.getPhone());
                                            ps.setInt(3, student.getStudentId());

                                            int updateResult = ps.executeUpdate();
                                            if (updateResult > 0) {
                                                System.out.println("个人信息更新成功！");
                                            } else {
                                                System.out.println("更新失败，请重试");
                                            }
                                        }
                                    } catch (SQLException e) {
                                        System.out.println("数据库错误: " + e.getMessage());
                                    }
                                    break;

                                case 3:
                                    System.out.println("已退出登录");
                                    logout = true;
                                    break;

                                default:
                                    System.out.println("无效选择，请重新输入");
                            }
                        }
                    } else {
                        System.out.println("登录失败，用户名或密码错误！");
                    }
                    break;

                case 2:
                    System.out.println("\n用户注册");
                    System.out.print("请输入用户名：");
                    String name = scanner.next();

                    System.out.print("请输入密码：");
                    String password = scanner.next();

                    System.out.print("请输入手机号码：");
                    String phone = scanner.next();

                    Student s = new Student();
                    s.setName(name);
                    s.setPassword(password);
                    s.setPhone(phone);

                    int insertResult = studentService.insertStudent(s);
                    if (insertResult > 0) {
                        System.out.println("注册成功！");
                    } else {
                        System.out.println("注册失败！");
                    }
                    break;

                case 3:
                    System.out.println("请输入管理员账号");
                    String username = scanner.next();
                    System.out.println("请输入密码");
                    String userpassword = scanner.next();

                    try {
                        Manager manager = managerService.selectManager(username, userpassword);
                        if (manager != null) {
                            System.out.println("管理员登录成功!");
                            adminMenu(scanner); // 进入管理员菜单
                        } else {
                            System.out.println("账号或密码错误!");
                        }
                    } catch (Exception e) {
                        System.out.println("登录异常: " + e.getMessage());
                    }
                    break;

                case 4:
                    System.out.println("感谢使用，再见！");
                    return;

                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    private static void adminMenu(Scanner scanner) {
        while (true) {
            System.out.println("管理员系统");
            System.out.println("1. 用户管理");
            System.out.println("2. 商品管理");
            System.out.println("3. 订单管理");
            System.out.println("4. 退出管理员系统");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            try {
                switch (choice) {
                    case 1:
                        manageUsers(scanner);
                        break;
                    case 2:
                        manageProducts(scanner);
                        break;
                    case 3:
                        manageOrders(scanner);
                        break;
                    case 4:
                        System.out.println("已退出管理员系统");
                        return;
                    default:
                        System.out.println("无效选项!");
                }
            } catch (SQLException e) {
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }

    private static void manageUsers(Scanner scanner) throws SQLException {
        while (true) {
            System.out.println("用户管理");
            System.out.println("1. 查看所有用户");
            System.out.println("2. 添加用户");
            System.out.println("3. 修改用户");
            System.out.println("4. 删除用户");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    List<Student> students = studentService.selectAllStudents();
                    System.out.println("ID\t用户名\t手机号");
                    for (Student s : students) {
                        System.out.printf("%d\t%s\t%s%n",
                                s.getStudentId(), s.getName(), s.getPhone());
                    }
                    break;

                case 2:
                    System.out.print("请输入用户名: ");
                    String name = scanner.next();
                    System.out.print("请输入密码: ");
                    String password = scanner.next();
                    System.out.print("请输入手机号: ");
                    String phone = scanner.next();

                    Student newStudent = new Student();
                    newStudent.setName(name);
                    newStudent.setPassword(password);
                    newStudent.setPhone(phone);

                    int addResult = studentService.insertStudent(newStudent);
                    System.out.println(addResult > 0 ? "用户添加成功!" : "用户添加失败!");
                    break;

                case 3:
                    System.out.print("请输入要修改的用户ID: ");
                    int updateId = scanner.nextInt();
                    Student studentToUpdate = studentService.getStudentById(updateId);
                    if (studentToUpdate == null) {
                        System.out.println("用户不存在!");
                        break;
                    }

                    System.out.print("请输入新用户名(原: " + studentToUpdate.getName() + "): ");
                    String newName = scanner.next();
                    System.out.print("请输入新密码(原: " + studentToUpdate.getPassword() + "): ");
                    String newPassword = scanner.next();
                    System.out.print("请输入新手机号(原: " + studentToUpdate.getPhone() + "): ");
                    String newPhone = scanner.next();

                    studentToUpdate.setName(newName);
                    studentToUpdate.setPassword(newPassword);
                    studentToUpdate.setPhone(newPhone);

                    int updateResult = studentService.updateStudent(studentToUpdate);
                    System.out.println(updateResult > 0 ? "用户修改成功!" : "用户修改失败!");
                    break;

                case 4:
                    System.out.print("请输入要删除的用户ID: ");
                    int deleteId = scanner.nextInt();
                    int deleteResult = studentService.deleteStudent(deleteId);
                    System.out.println(deleteResult > 0 ? "用户删除成功!" : "用户删除失败!");
                    break;

                case 5:
                    return;

                default:
                    System.out.println("无效选项!");
            }
        }
    }

    private static void manageProducts(Scanner scanner) throws SQLException {
        while (true) {
            System.out.println("商品管理");
            System.out.println("1. 查看所有商品");
            System.out.println("2. 添加商品");
            System.out.println("3. 修改商品");
            System.out.println("4. 删除商品");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    List<Product> products = productService.selectAllProduct();
                    System.out.println("ID\t名称\t价格\t库存\t类别\t描述");
                    for (Product p : products) {
                        System.out.printf("%d\t%s\t%.2f\t%d\t%s\t%s%n",
                                p.getProductId(),
                                p.getProductName(),
                                p.getPrice(),
                                p.getStock(),
                                p.getCategory(),
                                p.getDescription());
                    }
                    break;

                case 2:
                    System.out.print("请输入商品名称: ");
                    String name = scanner.next();
                    System.out.print("请输入商品价格: ");
                    double price = scanner.nextDouble();
                    System.out.print("请输入商品库存: ");
                    int stock = scanner.nextInt();
                    System.out.print("请输入商品类别: ");
                    String category = scanner.next();
                    System.out.print("请输入商品描述: ");
                    String description = scanner.next();

                    Product newProduct = new Product();
                    newProduct.setProductName(name);
                    newProduct.setPrice(price);
                    newProduct.setStock(stock);
                    newProduct.setCategory(category);
                    newProduct.setDescription(description);

                    int addResult = productService.insertProduct(newProduct);
                    System.out.println(addResult > 0 ? "商品添加成功!" : "商品添加失败!");
                    break;

                case 3:
                    System.out.print("请输入要修改的商品ID: ");
                    int updateId = scanner.nextInt();
                    Product productToUpdate = productService.getProductById(updateId);
                    if (productToUpdate == null) {
                        System.out.println("商品不存在!");
                        break;
                    }

                    System.out.print("请输入新名称(原: " + productToUpdate.getProductName() + "): ");
                    String newName = scanner.next();
                    System.out.print("请输入新价格(原: " + productToUpdate.getPrice() + "): ");
                    double newPrice = scanner.nextDouble();
                    System.out.print("请输入新库存(原: " + productToUpdate.getStock() + "): ");
                    int newStock = scanner.nextInt();
                    System.out.print("请输入新类别(原: " + productToUpdate.getCategory() + "): ");
                    String newCategory = scanner.next();
                    System.out.print("请输入新描述(原: " + productToUpdate.getDescription() + "): ");
                    String newDescription = scanner.next();

                    productToUpdate.setProductName(newName);
                    productToUpdate.setPrice(newPrice);
                    productToUpdate.setStock(newStock);
                    productToUpdate.setCategory(newCategory);
                    productToUpdate.setDescription(newDescription);

                    int updateResult = productService.updateProduct(productToUpdate);
                    System.out.println(updateResult > 0 ? "商品修改成功!" : "商品修改失败!");
                    break;

                case 4:
                    System.out.print("请输入要删除的商品ID: ");
                    int deleteId = scanner.nextInt();
                    int deleteResult = productService.deleteProduct(deleteId);
                    System.out.println(deleteResult > 0 ? "商品删除成功!" : "商品删除失败!");
                    break;

                case 5:
                    return;

                default:
                    System.out.println("无效选项!");
            }
        }
    }

    // 新增订单管理功能
    private static void manageOrders(Scanner scanner) throws SQLException {
        while (true) {
            System.out.println("\n===== 订单管理 =====");
            System.out.println("1. 查看所有订单");
            System.out.println("2. 删除订单");
            System.out.println("3. 返回上级菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            switch (choice) {
                case 1: // 查看所有订单
                    List<Order> orders = orderService.selectAllOrders();
                    System.out.println("订单ID\t学生ID\t商品ID\t数量\t总价");
                    for (Order o : orders) {
                        System.out.printf("%d\t%d\t%d\t%d\t%.2f%n",
                                o.getOrderId(),
                                o.getStudentId(),
                                o.getProductId(),
                                o.getNumber(),
                                o.getTotalPrice());
                    }
                    break;

                case 2:
                    System.out.print("请输入要删除的订单ID: ");
                    int orderId = scanner.nextInt();
                    int result = orderService.deleteOrder(orderId);
                    System.out.println(result > 0 ? "订单删除成功!" : "订单删除失败!");
                    break;

                case 3:
                    return;

                default:
                    System.out.println("无效选项!");
            }
        }
    }
}